package cn.com.yang.algorithm.v2;

import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.junit.Test;

import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.SecureRandom;
import java.security.spec.ECGenParameterSpec;
import java.util.Base64;

/**
 * @Author 杨亿金
 * @Date 2022/4/21 21:30
 * @CopyRight
 * @Version
 */
public class KeyPairUtil {

    /**
     * SM2算法生成密钥对
     * @return 密钥对信息
     */
    public  KeyPair generateSm2KeyPair() {
        try {
            final ECGenParameterSpec sm2Spec = new ECGenParameterSpec("sm2p256v1");
            // 获取一个椭圆曲线类型的密钥对生成器
            final KeyPairGenerator kpg = KeyPairGenerator.getInstance("EC", new BouncyCastleProvider());
            SecureRandom random = new SecureRandom();
            // 使用SM2的算法区域初始化密钥生成器
            kpg.initialize(sm2Spec, random);
            // 获取密钥对
            KeyPair keyPair = kpg.generateKeyPair();
            return keyPair;
        } catch (Exception e) {
            System.out.println("generate sm2 key pair failed:");
            return  null;
        }
    }

    @Test
    public void generateSm2KeyPairTest() {
        KeyPair keyPair = generateSm2KeyPair();
        System.out.println("私钥>>"+Base64.getEncoder().encodeToString(keyPair.getPrivate().getEncoded()));
        System.out.println("=======================");
        System.out.println("公钥>>"+Base64.getEncoder().encodeToString(keyPair.getPublic().getEncoded()));
        //System.out.println(Base64Utils.encode(keyPair.getPrivate().getEncoded()));
        //System.out.println(Base64Utils.encode(keyPair.getPublic().getEncoded()));
    }
}
